package com.beijiteshop.libcommon.network

import com.beijiteshop.libcommon.BuildConfig
import com.beijiteshop.libcommon.network.config.HeaderInterceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object RetrofitClient {

    private val BASE_URL
    get() = if (BuildConfig.DEBUG){
        "http://119.23.181.190/"
    }else{
        "http://119.23.181.190/"
    }

    private val mOkClient = OkHttpClient.Builder()
        .callTimeout(10, TimeUnit.SECONDS)//完整请求超时时长，从发起到接收返回数据，默认值0，不限定,
        .connectTimeout(10, TimeUnit.SECONDS)//与服务器建立连接的时长，默认10s
        .readTimeout(10, TimeUnit.SECONDS)//读取服务器返回数据的时长
        .writeTimeout(10, TimeUnit.SECONDS)//向服务器写入数据的时长，默认10s
        .retryOnConnectionFailure(true)//重连
        .addNetworkInterceptor(HeaderInterceptor())
        .addNetworkInterceptor(HttpLoggingInterceptor().apply {
            level = HttpLoggingInterceptor.Level.BODY
        })
        .build()

    private val mRetrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(mOkClient)
        .build()

    /**
     * 获取定义的retrofit接口
     */
    fun <T> getService(clazz: Class<T>): T{
        return mRetrofit.create(clazz)
    }
}